<template>
  <a-modal
    title="批量调动"
    :open="props.modelVisible"
    ok-text="确认"
    cancel-text="取消"
    @ok="onOk"
    @cancel="onCancel"
    :maskClosable="true"
  >
    <div class="modal-content">
      <p class="move-info">您选择了 <span class="student-count">{{ props.students?.length || 0 }}</span> 位学生进行调动</p>
      <a-form ref="formRef" :model="formState">
        <a-form-item
          label="目标小组"
          name="teamId"
          :rules="[{ required: true, message: '请选择小组' }]"
        >
          <a-select
            v-model:value="formState.teamId"
            placeholder="请选择小组"
            style="width: 100%"
            :field-names="{ label: 'teamName', value: 'teamId' }"
            :options="props.teams"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { message, type FormInstance } from 'ant-design-vue';
import UserDao from '@/daos/user_dao';

const userDao = new UserDao();
//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  classId: {
    type: Number
  },
  teams: {
    type: Array
  },
  students: {
    type: Array<number>
  }
});
//表单对象
const formState = reactive({
  teamId: undefined
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);
//定义表单
const formRef = ref<FormInstance>();
const onOk = () => {
  if (!props.classId) {
    message.error('班级ID不存在，无法移动学生');
    return;
  }
  
  if (!props.students || props.students.length === 0) {
    message.warning('未选择学生，无法执行移动操作');
    return;
  }

  formRef.value
    .validateFields()
    .then(() => {
      // 显示加载状态
      const hide = message.loading('正在移动学生...', 0);
      
      userDao.setTeamForStudents(props.classId, formState.teamId, props.students)
        .then((result) => {
          hide(); // 关闭加载提示
          
          if (result?.data?.code === 200) {
            message.success(result?.data?.msg || '学生移动成功');
            emit('confirm');
            emit('update:modelVisible', false);
          } else {
            message.error(result?.data?.msg || '移动学生失败');
          }
        })
        .catch((error) => {
          hide(); // 关闭加载提示
          console.error('移动学生失败:', error);
          message.error('移动学生失败，请检查网络连接');
        });
    })
    .catch((error) => {
      console.error('数据验证失败:', error);
    });
};
const onCancel = () => {
  // formRef.value.resetFields();
  emit('update:modelVisible', false);
};

watch(
  () => props.modelVisible,
  () => {
    if (props.modelVisible == true) {
      formState.teamId = undefined; // 重置表单值
    }
  }
);
</script>

<style scoped>
.modal-content {
  padding: 8px 0;
}
.move-info {
  margin-bottom: 16px;
  font-size: 14px;
}
.student-count {
  font-weight: bold;
  color: #1890ff;
}
</style>
